#include "info.h"
#include "../packet_headers/etherhdr.h"
#include "hw_translate.h"
#include "packet.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define ETH_HW_ADDR_LEN 6


char * get_local_mac(const char * _interface) {
	int fd;
	struct ifreq ifr;

	fd = socket(AF_INET, SOCK_DGRAM, 0);

	ifr.ifr_addr.sa_family = AF_INET;
	strncpy(ifr.ifr_ifrn.ifrn_name, _interface, strlen(_interface));
	ifr.ifr_ifrn.ifrn_name[strlen(_interface)] = 0;

	ioctl(fd, SIOCGIFHWADDR, &ifr);
	close(fd);

	char * HW_ADDR = new char[ETH_HW_ADDR_LEN];
	memcpy(HW_ADDR, ifr.ifr_ifru.ifru_addr.sa_data, ETH_HW_ADDR_LEN);

	return HW_ADDR;
}

unsigned int get_next_space(const char * _str, unsigned int _off) {
	unsigned int len = strlen(_str);
	unsigned int off = _off;
	while(off < len && _str[off] != ' ')
		off++;
	return off;
}

unsigned int skip_space(const char * _str, unsigned int _off) {
	unsigned int len = strlen(_str);
		unsigned int off = _off;
		while(off < len && _str[off] == ' ')
			off++;
		return off;
}

char * get_gateway_mac(const char * _interface) {
	char* gateway = NULL;

	FILE* fp = popen("netstat -rn", "r");
	char line[256]={0x0};

	while(fgets(line, sizeof(line), fp) != NULL) {
		char* destination;
		destination = strndup(line, 15);
		char* iface;
		iface = strndup(line + 73, 4);
	    // Find line with the gateway
		if(strncmp("0.0.0.0", destination, 7) == 0 && strncmp(iface, _interface, strlen(_interface)) == 0) {
			// Extract gateway
			gateway = strndup(line + 16, 15);
		}
		free(destination);
		free(iface);
	}

	pclose(fp);

	// Send ARP request; get MAC address of router
	char * mac;
	char arpcmd[11+strlen(gateway)];
	strncpy(arpcmd, "arp -n ", 11);
	strncpy(arpcmd+7, gateway, strlen(gateway));

	fp = popen(arpcmd, "r");
	// Skip first line
	fgets(line, sizeof(line), fp);
	fgets(line, sizeof(line), fp);
	// Skip preliminaries
	unsigned int i = 0;
	i = get_next_space(line, i);
	i = skip_space(line, i);
	i = get_next_space(line, i);
	i = skip_space(line, i);
	char str[17];
	strncpy(str, line+i, 17);
	mac = get_hw_addr(str);

	return mac;
}
